// components/classic/music/index.js
import {classicBeh} from "../classic-beh.js";

Component({
    /**
     * 组件的属性列表
     */
    behaviors: [classicBeh],
    properties: {
        src: String,
        title:String
    },

    /**
     * 组件的初始数据
     */
    data: {
        playing: false,
        animationStatus: 'paused',
        pauseSrc: 'image/music@pause.png',
        playSrc: 'image/music@play.png'
    },

    /**
     * 组件生命周期函数
     */
    attached() {
        this.Music = wx.getBackgroundAudioManager()
        this._recoverStatus()
        this._monitorSwitch()
    },

    /**
     * 组件的方法列表
     */
    methods: {
        onPlay() {
            if (!this.data.playing) {
                this.setData({
                    playing: true
                })
                this.Music.src = this.properties.src;
                this.Music.title = this.properties.title;
                this.Music.play()
            } else {
                this.setData({
                    playing: false
                })
                this.Music.pause()
            }
        },

        _recoverStatus() {
            if (this.Music.paused) {
                this.setData({
                    playing: false,
                    animationStatus: 'paused'
                })
                return
            }
            if (this.Music.src == this.properties.src) {
                this.setData({
                    playing: true,
                    animationStatus: 'running'
                })
            }
        },

        _monitorSwitch() {
            this.Music.onPlay(() => {
                console.log('正在播放')
                this._recoverStatus()
            })
            this.Music.onPause(() => {
                console.log('暂停播放')
                this._recoverStatus()
            })
            this.Music.onStop(() => {
                this._recoverStatus()
            })
            this.Music.onEnded(() => {
                this._recoverStatus()
            })
        }
    }
})
